// pages/shopping/uploading/uploading.js
const app = getApp()
const connector = require('../../../utils/connector.js')
const qiniuUploader = require('../../../utils/qiniuUploader.js')
  
let tok;
let upLoadImgUrl;

let authTok;//私有
let upLoadAuthImgUrl;//私有
// var sets;//监听websocket是否连接成功（轮询器）
// 初始化七牛相关参数
function initQiniu(toks, domain) {
  var options = {
   region: 'SCN', // 华南区
    // uptokenURL: 'https://minitest.17jxyx.com/api/v1/token/file/goods',
    uptoken: toks,
    uploadURL: 'https://up-z2.qbox.me/',
    domain: domain,
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bar_Height: wx.getSystemInfoSync().statusBarHeight + 45,
    arrNew:[
      {ind:0,name:"个人信息",id:"0"},
      {ind:1,name:"成绩单",id:"1"},
      {ind:2,name:"场地费",id:"2"},
      {ind:3,name:"补考发票",id:"3"}
    ],
    kem1:0,
    kem2:0,
    kem3:0,
    indexs:0,//当前显示页
    courses:0,//办理进程
    arrImage0:[
      {types:"sfzz",src:"https://data.xuanheng99.com/sampleGraph/15858926006344bb19.jpg",fileJudge:false,progressNum:0,upLoad:""},
      {types:"sfzf",src:"https://data.xuanheng99.com/sampleGraph/1585892637530c7578.jpg",fileJudge:false,progressNum:0,upLoad:""},
      {types:"yhk",src:"https://data.xuanheng99.com/sampleGraph/1585893377188655b7.jpg",fileJudge:false,progressNum:0,upLoad:""},
    ],//个人
    arrImage1:[
      {type:"1",upLoad:[]},
      {type:"2",upLoad:[]},
      {type:"3",upLoad:[]}
    ],//成绩单
    arrImage2:[
      {type:"1",upLoad:[]},
      {type:"2",upLoad:[]},
      {type:"3",upLoad:[]}
    ],//场地费
    arrImage3:[
      {type:"1",upLoad:[]},
      {type:"2",upLoad:[]},
      {type:"3",upLoad:[]}
    ],//补考发票
    site:"1",//是否上传场地费发票：1：不传；2：传
 

  },
    //单图片上传
    chatI(e) {
      var that = this;
      chatI(that, authTok, upLoadAuthImgUrl,"compensateCs/",e.currentTarget.dataset.types,e.currentTarget.dataset.upload);
      // chatI(that, tok, upLoadImgUrl,"compensateCs/",e.currentTarget.dataset.types,e.currentTarget.dataset.upload);
    },
    //多图片上传
    chatKm(e) {
      var that = this;
      chatIs(that, tok, upLoadImgUrl,"compensateCs/",e.currentTarget.dataset.types,e.currentTarget.dataset.upload);
    },
  //点击头部
  upLoadTopOne(e){
    let that = this
    let indexs = that.data.indexs
    let courses = that.data.courses
    let ind = e.currentTarget.dataset.ind
    let arrImage0 = that.data.arrImage0
    let arrImage1 = that.data.arrImage1
    let arrImage2 = that.data.arrImage2
    let arrImage3 = that.data.arrImage3
    let arrNew = that.data.arrNew
    let kemu1 = that.data.kemu1
    let kemu2 = that.data.kemu2
    let kemu3 = that.data.kemu3
    let clickId = arrNew[indexs].id



    
    console.log("点击下标：" + ind,"当前页下标：" + indexs,"最大：" + courses)
    if(ind <= courses && indexs < courses){
      if(clickId == 0){
        if(!arrImage0[0].upLoad || arrImage0[0].upLoad.error){
          showToasts("请上传身份证正面")
          return false;
        }
        if(!arrImage0[1].upLoad || arrImage0[1].upLoad.error){
          showToasts("请上传身份证反面")
          return false;
        }
        if(!arrImage0[2].upLoad || arrImage0[2].upLoad.error){
          showToasts("请上传银行卡")
          return false;
        }
      }
      if(clickId == 1){
        console.log(arrImage1[0])
        if(arrImage1[0].upLoad.length < 1 || arrImage1[0].upLoad[0].file.length < 1){
          showToasts("请上科目一成绩单")
          return false;
        }
        if(arrImage1[1].upLoad.length < 1 || arrImage1[1].upLoad[0].file.length < 1){
          showToasts("请上科目二成绩单")
          return false;
        }
        if(arrImage1[2].upLoad.length < 1 || arrImage1[2].upLoad[0].file.length < 1){
          showToasts("请上科目三成绩单")
          return false;
        }
      }
      if(clickId == 2){
        console.log(arrImage2[0])
        if(kemu2 == 2){
          if(arrImage2[1].upLoad.length < 1 || arrImage2[1].upLoad[0].file.length < 1){
            showToasts("请上科目二场地费收据")
            return false;
          }
        }
        if(kemu3 == 3){
          if(arrImage2[2].upLoad.length < 1 || arrImage2[2].upLoad[0].file.length < 1){
            showToasts("请上科目三场地费收据")
            return false;
          }
        }
      }
    }
    if(ind <= courses){
      that.setData({
        indexs:e.currentTarget.dataset.ind
      })
      console.log(ind,courses,indexs)
    }
    

  },
  //下科目一步
  optionBotNext(e){
    let that = this;
    let indexs = that.data.indexs
    let courses = that.data.courses
    let arrImage0 = that.data.arrImage0
    let arrImage1 = that.data.arrImage1
    let arrImage2 = that.data.arrImage2
    let arrNew = that.data.arrNew
    let kemu2 = that.data.kemu2
    let kemu3 = that.data.kemu3
    if(courses == indexs){
      courses+=1
    }
    let clickId = arrNew[indexs].id
    console.log(arrImage0)
    console.log(arrImage1)
    if(clickId == 0){
      if(!arrImage0[0].upLoad || arrImage0[0].upLoad.error){
        showToasts("请上传身份证正面")
        return false;
      }
      if(!arrImage0[1].upLoad || arrImage0[1].upLoad.error){
        showToasts("请上传身份证反面")
        return false;
      }
      if(!arrImage0[2].upLoad || arrImage0[2].upLoad.error){
        showToasts("请上传银行卡")
        return false;
      }
    }
    if(clickId == 1){
      console.log(arrImage1[0])
      if(arrImage1[0].upLoad.length < 1 || arrImage1[0].upLoad[0].file.length < 1){
        showToasts("请上科目一成绩单")
        return false;
      }
      if(arrImage1[1].upLoad.length < 1 || arrImage1[1].upLoad[0].file.length < 1){
        showToasts("请上科目二成绩单")
        return false;
      }
      if(arrImage1[2].upLoad.length < 1 || arrImage1[2].upLoad[0].file.length < 1){
        showToasts("请上科目三成绩单")
        return false;
      }
    }
    if(clickId == 2){
      console.log(arrImage2[0])
      if(kemu2 == 2){
        if(arrImage2[1].upLoad.length < 1 || arrImage2[1].upLoad[0].file.length < 1){
          showToasts("请上科目二场地费收据")
          return false;
        }
      }
      if(kemu3 == 3){
        if(arrImage2[2].upLoad.length < 1 || arrImage2[2].upLoad[0].file.length < 1){
          showToasts("请上科目三场地费收据")
          return false;
        }
      }
    }
    that.setData({
      indexs:indexs + 1,
      courses:courses
    })

  },
  //上科目一步
  optionBotBtnLast(e){
    let that = this;
    let indexs = that.data.indexs
    that.setData({
      indexs:indexs -1
    })
  },
  //提交
  submitBtn(e){
    let that = this
    let arrImage0 = that.data.arrImage0
    let arrImage1 = that.data.arrImage1
    let arrImage2 = that.data.arrImage2
    let arrImage3 = that.data.arrImage3
    let kemu1 = that.data.kemu1
    let kemu2 = that.data.kemu2
    let kemu3 = that.data.kemu3
    if(kemu1 == 1){
      if(arrImage3[0].upLoad.length < 1 || arrImage3[0].upLoad[0].file.length < 1){
        showToasts("请上科目一补考发票")
        return false;
      }
    }
    if(kemu2 == 2){
      if(arrImage3[1].upLoad.length < 1 || arrImage3[1].upLoad[0].file.length < 1){
        showToasts("请上科目二补考发票")
        return false;
      }
    }
    if(kemu3 == 3){
      if(arrImage3[2].upLoad.length < 1 || arrImage3[2].upLoad[0].file.length < 1){
        showToasts("请上科目三补考发票")
        return false;
      }
    }
    // console.log(arrImage0)
    // console.log(arrImage1)
    // console.log(arrImage2)
    // console.log(arrImage3)
    let arrUsers = {
      front:arrImage0[0].upLoad.imageURL,
      back:arrImage0[1].upLoad.imageURL,
      bank_img:arrImage0[2].upLoad.imageURL
    };
    
    let arrlist = []
    for(let i = 0;i<arrImage1.length;i++){
      for(let j = 0;j<arrImage1[i].upLoad.length;j++){
        let obj = {
          type:"2",
          subject:arrImage1[i].type,
          URL:arrImage1[i].upLoad[j].file[0].imageURL
        }
        arrlist.push(obj)
      }
    }
    for(let i = 0;i<arrImage2.length;i++){
      if(arrImage2[i].upLoad.length > 0){
        for(let j = 0;j<arrImage2[i].upLoad.length;j++){
          let obj = {
            type:"1",
            subject:arrImage2[i].type,
            URL:arrImage2[i].upLoad[j].file[0].imageURL
          }
          arrlist.push(obj)
        }
      }
    }
    for(let i = 0;i<arrImage3.length;i++){
      for(let j = 0;j<arrImage3[i].upLoad.length;j++){
        let obj = {
          type:"3",
          subject:arrImage3[i].type,
          URL:arrImage3[i].upLoad[j].file[0].imageURL
        }
        arrlist.push(obj)
      }
    }
    let objAll = {
      user_info:arrUsers,
      detail:arrlist,
      course:that.data.arrNews
    }
    vipUserApply(that,objAll)
    console.log(objAll)
    
  },
  //返回
  optionBotBtnBack(e){
    wx.navigateBack({
      delta: 1,
    })
  },
  //删除上传的图片
  delFiles(e){
    let that = this;
    let types = e.currentTarget.dataset.types //65e
    let upload = e.currentTarget.dataset.upload //65e
    let key = e.currentTarget.dataset.key //65e
    let arrNewImage = []
    if(upload == "arrImage1"){
      arrNewImage = that.data.arrImage1
    }
    if(upload == "arrImage2"){
      arrNewImage = that.data.arrImage2
    }
    if(upload == "arrImage3"){
      arrNewImage = that.data.arrImage3
    }
    for (let i = 0; i < arrNewImage.length; i++){
      if(arrNewImage[i].type == types){
        for(let j = 0;j<arrNewImage[i].upLoad.length;j++){
          if(arrNewImage[i].upLoad[j].key == key){
            arrNewImage[i].upLoad.splice(j, 1)
          }
        }
      }
    }
    if(upload == "arrImage1"){
      that.setData({
        arrImage1:arrNewImage,
      })
    }
    if(upload == "arrImage2"){
      that.setData({
        arrImage2:arrNewImage,
      })
    }
    if(upload == "arrImage3"){
      that.setData({
        arrImage3:arrNewImage,
      })
    }
    connector.deleteFile(key,app.tokens)

    // console.log(arrNewImage)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    console.log(options)
    let arrNews = JSON.parse(options.arr)
    let site = options.site
    console.log(site)
    //  let arrNews = ["1", "3", "4"]
    let arrNew = that.data.arrNew
    console.log(arrNews)
    if((arrNews.length == 1 && arrNews[0] == 1) || site == 1){
      arrNew = [
        {ind:0,name:"个人信息",id:"0"},
        {ind:1,name:"成绩单",id:"1"},
        {ind:2,name:"补考发票",id:"3"}
      ]
    }
    let kemu1 = 0,kemu2=0,kemu3=0;
    for(let i=0;i<arrNews.length;i++){
      if(arrNews[i] == 1){
        kemu1 = 1
      }
      if(arrNews[i] == 2){
        kemu2 = 2
      }
      if(arrNews[i] == 3){
        kemu3 = 3
      }
    }
    that.setData({
      arrNew:arrNew,
      arrNews:arrNews,
      kemu1:kemu1,
      kemu2:kemu2,
      kemu3:kemu3,
      upLoadTopOne:730/arrNew.length,
      site:site
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    connector.getFunc(app.conUser + connector.connector().filePath, "", "post", app.tokens,function(res){
      tok = res.data[0].upToken
      upLoadImgUrl = res.data[0].domain
    },function(res){
      console.log(res)
    })

    //私有
    connector.getFunc(app.conUser + connector.connector().fileAuthPath, "", "post", app.tokens,function(res){
      authTok = res.data[0].upToken
      upLoadAuthImgUrl = res.data[0].domain
    },function(res){
      console.log(res)
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

})
//单图片上传 token:七牛上传token;types:上传文件前缀
//(token:七牛token  domain：域名  types：七牛保存分类头名  imgTypes：文件上传小分类  upLoadType:上传大分类)
function chatI(that, token, domain,types,imgTypes,upLoadTypes) {
  initQiniu(token, domain);
  console.log(token, domain)
  let arrImage =[]
  if(upLoadTypes == "arrImage0"){
    arrImage = that.data.arrImage0
  }
  // 微信 API 选文件
  wx.chooseImage({
    count: 1,
    success: function (res) {
      console.log(res)
      let filePath = res.tempFilePaths[0];
      for(let i=0;i<arrImage.length;i++){
        if(arrImage[i].types == imgTypes){
          arrImage[i].src = filePath
          arrImage[i].fileJudge = true
         
        }
      }
      
      // arrImage.src = filePath
      if(upLoadTypes == "arrImage0"){
        that.setData({
          arrImage0: arrImage,
        })
      }
     
    let houzhui = filePath.lastIndexOf(".")
    let sss = filePath.slice(houzhui)
    let keys = filePath.slice(houzhui - 5, houzhui)
    let timestamp = (new Date()).getTime();
    let fileName = types + timestamp + keys + sss
      
      // 交给七牛上传
      qiniuUploader.upload(filePath, fileName,(ser) => {
        console.log(ser)
        for(let i=0;i<arrImage.length;i++){
          if(arrImage[i].types == imgTypes){
            if(arrImage[i].upLoad){
              connector.deleteFileAuth(arrImage[i].upLoad.key,app.tokens)
            }
            arrImage[i].upLoad = ser
          }
        }
        if(upLoadTypes == "arrImage0"){
          that.setData({
            arrImage0: arrImage,
          })
        }
      }, (error) => {
        console.error('error: ' + JSON.stringify(error));
      },
        null,// 可以使用上述参数，或者使用 null 作为参数占位符
        (progress) => {
          console.log(progress)
          for(let i=0;i<arrImage.length;i++){
            if(arrImage[i].types == imgTypes){
              arrImage[i].progressNum = progress.progress
              if(progress.progress == 100){
                arrImage[i].fileJudge = false
                console.log(arrImage)
              }
            }
          }
          if(upLoadTypes == "arrImage0"){
            that.setData({
              arrImage0: arrImage,
            })
          }
          // that.setData({
          //   progressNum: progress.progress
          // })
          // console.log('上传进度', progress.progress)
          // console.log('已经上传的数据长度', progress.totalBytesSent)
          // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
          // if (progress.progress == 100){
          //   that.setData({
          //     fileJudge:false
          //   })
          // }
        }, cancelTask => that.setData({ cancelTask })
      );
    }
  })
}
// //删除七牛云图片
// function deleteFile(fileKey){
//   console.log(fileKey)
//   let obj = {
//     fileName: fileKey
//   }
//   connector.getFunc(app.conUser + connector.connector().fileDelete, obj, "post", app.tokens, function (res) {
//     // console.log(res.data[0].upToken)
//     console.log(res)

//   }, function (res) {
//     console.log(res)
//   })
// }
//多图片上传 token:七牛上传token;types:上传文件前缀
function chatIs(that, token, domain,types,imgTypes,upLoadTypes) {
  initQiniu(token, domain);
  let arr = []
  if(upLoadTypes == "arrImage1"){
    arr = that.data.arrImage1
  }
  if(upLoadTypes == "arrImage2"){
    arr = that.data.arrImage2
  }
  if(upLoadTypes == "arrImage3"){
    arr = that.data.arrImage3
  }
  // 微信 API 选文件
  let objNew = {}
  wx.chooseImage({
    count: 1,
    success: function (res) {
      let filePath = res.tempFilePaths[0];
      let houzhui = filePath.lastIndexOf(".")
      let sss = filePath.slice(houzhui)
      let keys = filePath.slice(houzhui - 5, houzhui)
      let timestamp = (new Date()).getTime();
      let fileName = types + timestamp + keys + sss
      for(let i=0;i<arr.length;i++){
        if(arr[i].type == imgTypes){
          objNew.tempFilePaths = filePath
          objNew.key = fileName
          objNew.fileJudge = true
          objNew.file = []
          objNew.progressNum = 0
          arr[i].upLoad.push(objNew)
        }
      }
      if(upLoadTypes == "arrImage1"){
        that.setData({
          arrImage1:arr,
        })
      }
      if(upLoadTypes == "arrImage2"){
        that.setData({
          arrImage2:arr,
        })
      }
      if(upLoadTypes == "arrImage3"){
        that.setData({
          arrImage3:arr,
        })
      }
      //交给七牛上传
      qiniuUploader.upload(filePath, fileName,(ser) => {
        // console.log(ser)
        // let fileArrNew = that.data.fileArr
        for (let i = 0; i < arr.length; i++){
          if(arr[i].type == imgTypes){
            for(let j = 0;j<arr[i].upLoad.length;j++){
              if(arr[i].upLoad[j].key == ser.key){
                arr[i].upLoad[j].fileJudge = false
                arr[i].upLoad[j].file.push(ser) 
              }
            }
          }
        }
        if(upLoadTypes == "arrImage1"){
          that.setData({
            arrImage1:arr,
          })
        }
        if(upLoadTypes == "arrImage2"){
          that.setData({
            arrImage2:arr,
          })
        }
        if(upLoadTypes == "arrImage3"){
          that.setData({
            arrImage3:arr,
          })
        }
      }, (error) => {
        // console.error('error: ' + JSON.stringify(error));
      },
      null,// 可以使用上述参数，或者使用 null 作为参数占位符
      (progress) => {
        that.setData({
          progressNum: progress.progress
        })
        for (let i = 0; i < arr.length; i++){
          if(arr[i].type == imgTypes){
            for(let j = 0;j<arr[i].upLoad.length;j++){
              if(arr[i].upLoad[j].key == progress.fileName){
                arr[i].upLoad[j].progressNum = progress.progress
              }
            }
          }
        }
        if(upLoadTypes == "arrImage1"){
          that.setData({
            arrImage1:arr,
          })
        }
        if(upLoadTypes == "arrImage2"){
          that.setData({
            arrImage2:arr,
          })
        }
        if(upLoadTypes == "arrImage3"){
          that.setData({
            arrImage3:arr,
          })
        }
      }, cancelTask => that.setData({ cancelTask })
      );
    }
  })
}
//提示
function showToasts(str){
  wx.showToast({
    title: str,
    icon: 'none',
    duration: 1000//持续的时间
  })
}
//理赔提交
function vipUserApply(that,obj){
  // vip_status是否购买理赔；0：未购买；1：科目一
  connector.getFunc(connector.connector().vipUserApply, obj, "post", app.tokens, function (res) {
    console.log(res)
    if (res.statusCode == 200) {
      wx.showModal({
        title: '提示',
        content: '理赔信息提交成功，我司将在1-3个工作日内审核，如有疑问请联系我司工作人员：19907774410',
        success: function (res) {
          if (res.confirm) {
            // console.log('用户点击确定')
            // wx.navigateBack({
            //   delta: 1,
            // })
            wx.switchTab({
              url: '/pages/shopping/shopping',
            })
          } else if (res.cancel) {
            wx.switchTab({
              url: '/pages/shopping/shopping',
            })
            // console.log('用户点击取消')
            // wx.navigateBack({
            //   delta: 1,
            // })
          }
        }
      })
    }
  }, function (res) {
    wx.showToast({
      title: "内部错误",
      icon: 'none',
      duration: 1000
    })
  })
}